package com.woniu.order.consnmer;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.exception.RebornException;
import com.woniu.exception.order.OrderException;
import com.woniu.model.Result;
import com.woniu.order.client.FlowClient;
import com.woniu.order.cliententity.entity.FlowHandle;
import com.woniu.order.cliententity.form.AddHandelForm;
import com.woniu.order.mapper.TDownpaymentMapper;
import com.woniu.order.mapper.TOrderMapper;
import com.woniu.order.model.TDownpayment;
import com.woniu.order.model.TOrder;
import com.woniu.order.util.AlipayUtil;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Component
@RabbitListener(queues = "del_queue")
public class OrderNumQueueConsumer {
    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayUtil alipayUtil;

    @Resource
    private TDownpaymentMapper tDownpaymentMapper;

    @Resource
    private TOrderMapper orderMapper;

    @Resource
    private FlowClient flowClient;

    @Transactional
    @RabbitHandler
    public void checkOrder(String orderNum) throws Exception {
        System.out.println("消费者"+orderNum);
        System.out.println("=====================消费者====================");
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNum + "\"}");
        //请求
        String result = alipayUtil.config().execute(alipayRequest).getBody();
        System.out.println(result);
        //输出
        String orderInfo = JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
        String payCode = JSONUtil.parseObj(orderInfo).get("code").toString();

        //查询押金订单
        QueryWrapper<TDownpayment> wrapper = new QueryWrapper<>();
        wrapper.eq("downpayment_num",orderNum);
        TDownpayment tDownpayment = tDownpaymentMapper.selectOne(wrapper);

        if ("10000".equals(payCode)) {
            String payDate = JSONUtil.parseObj(orderInfo).get("send_pay_date").toString();
            String status = JSONUtil.parseObj(orderInfo).get("trade_status").toString();

            //支付后订单为已支付状态
            if (status.equals("TRADE_SUCCESS")) {

                tDownpayment.setPayState(1);
                //修改支付时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime parse = LocalDateTime.parse(payDate, formatter);
                tDownpayment.setPayTime(parse);

                tDownpaymentMapper.updateById(tDownpayment);

                //获取流程
                Result<FlowHandle> flowHandleResult = flowClient.locationConfirm(tDownpayment.getOrderNum());
                if (flowHandleResult.getCode()!=200){
                    throw new RebornException(flowHandleResult.getMessage(),flowHandleResult.getCode());
                }
                //判断是否有流程
                if (flowHandleResult.getData()==null){
                    //新增流程执行
                    AddHandelForm addHandelForm = new AddHandelForm(1, 1, null, tDownpayment.getOrderNum(), null);
                    Result<FlowHandle> add = flowClient.add(addHandelForm);
                    System.out.println(JSONUtil.toJsonStr(add));
                    if (add.getCode()!=200){
                        throw new OrderException(add.getCode(),add.getMessage());
                    }
                }




            }
        } else {
            //用户未对订单进行支付
            //取消订单，删除数据
            orderMapper.deleteById(tDownpayment.getOrderNum());
            tDownpaymentMapper.deleteById(tDownpayment);
        }
    }
}
